// 导入模板
import art from './index.art';
import axios from '../../api/request';
import { getToken, getUser,removeToken,removeUser } from "../../utils/storageUtils";

async function changePage(page){
    let pageNow = page || 1;
    let limit = 5;
    // axios发送请求
    let {data:{users,total}}= await axios({
        url:`/admin/user/${pageNow}/${limit}`,
    })
    let pageCount = Math.ceil(total/limit);
    // 遍历
    // 传入动态数据
    const html  = art({username:getUser().username,users,total,limit,pageNow,pageCount});
    // 渲染页面
    document.getElementById('app').innerHTML = html;

    // 添加删除功能
    deleteUser(page)




}

changePage(1);

// 注册全局函数
window.changePage = changePage;
window.updataPage = updataPage;
window.logOut = logOut;

function deleteUser(page){
    // dom节点渲染完成后才能获取
    let delBtns = document.querySelectorAll('.delBtn');

    delBtns.forEach(item=>{
        item.addEventListener('click',async ()=>{
            

            if(!confirm('确定删除吗'))return;

            // 发送axios请求 - 删除指定数据 - id
            let id = item.dataset.id;

           let {data} =await axios({
                url:`/admin/user/${id}`,
                method:'delete',
            })

            // console.log(res);
            if(data.code === 2000){
                alert('删除成功')
                // window.location.reload();
                changePage(page)
            }
            


        })
    })
}

function updataPage(id){
    // console.log(id);

    window.location.href = `/userUpdate.html#${id}`

}

function logOut(){
    // console.log("退出");
    removeToken()
    removeUser()

    window.location.href = '/login.html'
}

